part of pda.page;

class PageCheckDetail extends StatefulWidget {
  final CheckBill bill;

  PageCheckDetail(this.bill);

  @override
  State<StatefulWidget> createState() {
    return _PageCheckDetailState();
  }
}

class _PageCheckDetailState extends State<PageCheckDetail> {
  CheckBill bill;
  List<CheckBillItem> items;
  Offset touchPoint;
  bool selectAll;
  final Map<bool, Icon> selectAllIcons = {
    false: Icon(Icons.check_box_outline_blank),
    true: Icon(Icons.check_box),
  };
  Map<String, bool> selected = {};

  @override
  void initState() /*async*/ {
    // initState 方法不能是 async 的
    super.initState();
    bill = widget.bill ?? CheckBill();
    selectAll = false;
    items = [];
//    items = bill.id == null ? [] : await bill.loadItems();
//    if (items != null && items.isNotEmpty) {
//      items.forEach((item) => selected[item.id] = false);
//    }
  }

  Future<List<CheckBillItem>> loadItems() async {
    if (bill == null || bill.id == null) return [];
    items = (await bill.loadItems()) ?? [];
    if (items.isNotEmpty) {
      items.forEach((item) => selected[item.id] = false);
    }
    return items;
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      child: Scaffold(
        appBar: AppBar(
          title: Text('盘点单'),
        ),
        body: Column(
          children: <Widget>[
            Text('盘点日期:${bill.checkDate}'),
            Text('盘点部门:${bill.depart}'),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: <Widget>[
                FlatButton.icon(
                    onPressed: toggleSelectAll,
                    icon: selectAllIcons[selectAll],
                    label: Text('全选')),
                FlatButton.icon(
                    onPressed: () {
                      Navigator.push(context, MaterialPageRoute(builder: (_) {
                        return PageCheckItem(bill);
                      }));
                    },
                    icon: Icon(Icons.add_circle),
                    label: Text('增加')),
                FlatButton.icon(
                    onPressed: () {},
                    icon: Icon(Icons.delete_forever),
                    label: Text('删除')),
              ],
            ),
            itemList(),
          ],
        ),
        floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
        floatingActionButton: FloatingActionButton(
          mini: true,
          onPressed: () {
            showModalBottomSheet(
                context: context,
                builder: (context) {
                  return Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: Column(
                      mainAxisSize: MainAxisSize.min,
                      children: actionSheetItems(),
                    ),
                  );
                });
          },
          child: GestureDetector(
            child: Icon(Icons.menu),
            onPanDown: (details) {
              touchPoint = details.globalPosition;
            },
          ),
        ),
      ),
      onWillPop: () async {
        return true;
      },
    );
  }

  toggleSelectAll() {
    setState(() {
      selectAll = !selectAll;
      selected.keys.forEach((key) => selected[key] = selectAll);
    });
  }

  Widget itemList() {
    List<Widget> makeListItems(List<CheckBillItem> items) {
      List<Widget> list = [];
      items.forEach((item) {
        list.add(ListTile(
          contentPadding: EdgeInsets.symmetric(horizontal: 0.0),
          onTap: () {
            debugPrint('onTap');
            toggleSelect('1');
          },
          leading: Checkbox(
            value: isSelected('1'),
            onChanged: (checked) {
              debugPrint('onChanged');
              toggleSelect('1');
            },
//              tristate: true,
          ),
          title: Text('单号11234567890'),
          subtitle: Text('部门1/盘点日期1'),
//            selected: true,
          trailing:
              IconButton(icon: Icon(Icons.arrow_forward_ios), onPressed: () {}),
        ));
        list.add(Divider());
      });
      return list.isEmpty
          ? [
              Padding(
                padding:
                    const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
                child: Text('单据明细为空'),
              )
            ]
          : list;
    }

    return FutureBuilder(
      future: loadItems(),
      builder: (context, snapshot) {
        if (snapshot.hasData) {
          return Expanded(
            child: ListView(
              padding: EdgeInsets.symmetric(horizontal: 0),
              children: makeListItems(snapshot.data),
            ),
          );
        } else {
          return Expanded(child: Text('正在加载...'));
        }
      },
    );
    return Expanded(
      child: ListView(
        padding: EdgeInsets.symmetric(horizontal: 0),
        children: <Widget>[
          ListTile(
            contentPadding: EdgeInsets.symmetric(horizontal: 0.0),
            onTap: () {
              debugPrint('onTap');
              toggleSelect('1');
            },
            leading: Checkbox(
              value: isSelected('1'),
              onChanged: (checked) {
                debugPrint('onChanged');
                toggleSelect('1');
              },
//              tristate: true,
            ),
            title: Text('单号11234567890'),
            subtitle: Text('部门1/盘点日期1'),
//            selected: true,
            trailing: IconButton(
                icon: Icon(Icons.arrow_forward_ios), onPressed: () {}),
          ),
          Divider(),
          ListTile(
            contentPadding: EdgeInsets.symmetric(horizontal: 0.0),
            onTap: () {
              debugPrint('onTap');
              toggleSelect('2');
            },
            leading: Checkbox(
              value: isSelected('2'),
              onChanged: (checked) {
                debugPrint('onChanged');
                toggleSelect('2');
              },
            ),
            title: Text('单号2'),
            subtitle: Text('部门2/盘点日期2'),
//            selected: true,
            trailing: IconButton(
                icon: Icon(Icons.arrow_forward_ios), onPressed: () {}),
          ),
          Divider(),
          Text('1'),
          Text('1'),
          Text('1'),
          Text('1'),
          Text('1'),
          Text('1'),
          Text('1'),
          Text('1'),
          Text('1'),
          Text('1'),
          Text('1'),
          Text('1'),
          Text('1'),
          Text('1'),
          Text('1'),
          Text('1'),
          Text('1'),
          Text('1'),
          Text('1'),
        ],
      ),
    );
  }

  toggleSelect(var id) {
    setState(() {
      selected[id] = !(selected[id] ?? false);
    });
  }

  isSelected(var id) => selected[id] ?? false;

  List<Widget> actionSheetItems() {
    List<Widget> items = [
      Row(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: <Widget>[
          FlatButton.icon(
              onPressed: () {},
              icon: Icon(Icons.cloud_upload),
              label: Text('上传单据')),
          FlatButton.icon(
              onPressed: () {},
              icon: Icon(Icons.remove_circle_outline),
              label: Text('删除此单')),
        ],
      ),
    ];
    return items;
  }
}
